package com.zzptc.zzsgz.bdsjws.utils;


import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.ContactsContract;
import android.support.v4.content.ContextCompat;

import com.zzptc.zzsgz.bdsjws.MyApplication;
import com.zzptc.zzsgz.bdsjws.db.MobileInfoDao;
import com.zzptc.zzsgz.bdsjws.vo.Contact;
import com.zzptc.zzsgz.bdsjws.vo.MobileInfo;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


//普通JAVA类，是没有上下文
public class MyUtil {
    //返回共享首选项对象
    public static SharedPreferences getSharedPre(){
         //获取上下文  再获取共享首选项
        return  MyApplication.getContext().getSharedPreferences("loginnew", Context.MODE_PRIVATE);
    }

    public boolean isSD(){
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            return true;
        }
            return false;
        }


    //得到文件的路径
    public  File getDir(){
        if (isSD()){
            return Environment.getExternalStorageDirectory();
        }
        return Environment.getDownloadCacheDirectory();
    }

    public static Intent getInstallintent(File file){
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
        MyApplication.getContext().startActivity(intent);
        return intent;
    }


    //获取版本号的方法
    public static int getVersionCode(Context context){
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName() , 0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return 0;
        }
    }




    //计算两个日期之间相差的天数
    public static int daysBetween(Date smdate,Date bdate) throws ParseException
    {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        smdate=sdf.parse(sdf.format(smdate));
        bdate=sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);

        return Integer.parseInt(String.valueOf(between_days));
    }


    public static Drawable getBBXIcon(String functionPic){
        Context context = MyApplication.getContext();
        int resId = context.getResources().getIdentifier(functionPic , "mipmap" , context.getPackageName());

        Drawable drawable = ContextCompat.getDrawable(context , resId);
        return drawable;
    }



    //复制文件到手机
//    public static void copyFileToMobile(Context context , String todbname) throws Exception{
//        //原始文件夹位置
//        URL url = context.getClass().getClassLoader().getResource("assets/" + todbname);
//        String dbfiledir = "/data/data/" + MyApplication.getContext().getPackageName()+"/data111";
//
//        File fileMobiledir = new File(dbfiledir);
//        if (!fileMobiledir.exists()){
//            fileMobiledir.mkdir();
//        }
//
//        File dbfileMobile = new File(fileMobiledir+"/"+todbname);
//        if (!dbfileMobile.exists()){
//            dbfileMobile.createNewFile();
//        }
//
//        FileUtils.copyURLToFile(url , dbfileMobile);
//
//    }




    //复制文件
    public static void copyFileToMobile (Context context , String fromdbname , String todbname) throws Exception{
                //原始文件夹位置
        URL url = context.getClass().getClassLoader().getResource("assets/" + fromdbname);
        String dbfiledir = "/data/data/" + MyApplication.getContext().getPackageName()+"/databases";

        File fileMobiledir = new File(dbfiledir);
        if (!fileMobiledir.exists()){
            fileMobiledir.mkdir();
        }

        File dbfileMobile = new File(fileMobiledir+"/"+todbname);
        if (!dbfileMobile.exists()){
            dbfileMobile.createNewFile();
        }

        FileUtils.copyURLToFile(url , dbfileMobile);

    }






    public static List<Contact> getAllContacts(){
        List<Contact> lists = new ArrayList<Contact>();
        ContentResolver contentResolver = MyApplication.getContext().getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
        if (cursor != null){
            while (cursor.moveToNext()){
                int id = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));//手机id
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));//手机联系人
                int num = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

                String phonenum = null;
                //如果大于0 就表示有电话号码
                if (num > 0){
                    phonenum = getPhonenumByID(id);
                }
                //获取手机归属地
               //准备工作: 将外部的数据库要拷贝到项目中  1.在哪里调用方法 MyAppication  2.使用greendao框架来调用外部数据库
                String addr = null;
                addr = getAddressByTel(phonenum);

                Contact contact = new Contact(id,name,phonenum,addr);
                lists.add(contact);
            }
            cursor.close();
        }
                return lists;
    }


    /**
     * 根据id来查询手机号码
     * @param
     * @return
     */
    //正则表达式 来判断这个是手机号码还是座机号码
    private static String getAddressByTel(String tel){
//        String telnum = tel.replace("" , "").replace("-","").substring(0,7);
//        MobileInfo mobileInfo = MyApplication.getMobileDaoSession().getMobileInfoDao().queryBuilder().
//                where(MobileInfoDao.Properties.MobileNumber.eq(telnum)).distinct().unique();

        MobileInfo mobileInfo = null;
//        String [] aa = tel.split(" ");
        String newtel = tel.replace(" " , "").replace("-","");
        String telnum = null;
        if (newtel.length() == 11&&newtel.matches("^1[3578]\\d{9}$")){
            //手机号码
          telnum = newtel.substring(0,7);   //截取前七位
            mobileInfo = MyApplication.getMobileDaoSession().getMobileInfoDao().queryBuilder()
                    .where(MobileInfoDao.Properties.MobileNumber.eq(telnum)).distinct().unique();

        }else{
            //座机号码
            int length = newtel.length();
            switch (length){
                case 10:
                    mobileInfo = MyApplication.getDaoSession().getMobileInfoDao().queryBuilder()
                            .where(MobileInfoDao.Properties.AreaCode.eq(newtel.substring(0,3))).limit(1).distinct().unique();
                    break;
                case 11:
                    //两种情况  3+7  4+7
                    mobileInfo = MyApplication.getDaoSession().getMobileInfoDao().queryBuilder()
                            .where(MobileInfoDao.Properties.AreaCode.eq(newtel.substring(0,3))).limit(1).distinct().unique();
                    if (mobileInfo == null){
                        mobileInfo = MyApplication.getDaoSession().getMobileInfoDao().queryBuilder()
                                .where(MobileInfoDao.Properties.AreaCode.eq(newtel.substring(0,4))).limit(1).distinct().unique();
                    }
                    break;
                case 12:
                    mobileInfo = MyApplication.getDaoSession().getMobileInfoDao().queryBuilder()
                            .where(MobileInfoDao.Properties.AreaCode.eq(newtel.substring(0,4))).limit(1).distinct().unique();
                    break;

            }

        }

        return mobileInfo.getMobileArea();
    }



    public static String getPhonenumByID(int id){
        String telnumm = null;
        ContentResolver contentResolver = MyApplication.getContext().getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"=?",new String[]{id+""},null);
        if (cursor != null){
            //只取一个电话号码
            if (cursor.moveToNext()){
                telnumm = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
        }
        cursor.close();
        return telnumm;
    }


}
